package com.atguigu.rabbitmq.springbootmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


/**
 * @description: TODO 发布确认 回调方法 当生产者 发送到交换机会触发此方法
 * @author zhangbanglong
 * @date 2024/1/14 9:07
 * @version 1.0
 */
@Slf4j
@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback ,RabbitTemplate.ReturnsCallback{

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @PostConstruct
    private void init(){
        rabbitTemplate.setReturnsCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String id=correlationData!=null?correlationData.getId():"";
        if(ack){
            log.info("交换机已经收到id={}的消息",id);
        }else {
            log.info("交换机还未收到id={}的消息，原因{}",id,cause);
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {

        log.info("消息：{}被服务器退回，退回原因：{},交换机是{},路由key{}",returnedMessage.getMessage().getBody(),returnedMessage.getReplyText(),returnedMessage.getExchange(),returnedMessage.getRoutingKey());
    }
}
